/**
 * Created by yang on 15/1/12.
 */


var Deferred = require('node-promise').Deferred;

var dslfiyPromise = function(promise,dsl){
    //console.log(dsl);
    for(var i in dsl){
        if(promise[i]){
            console.log(new Error('redefine promise method',i));
        }else{
            promise[i] = dsl[i];
        }
    }
    //promise._then = promise.then;
    //promise.then = function(params){
    //    console.log('promise then');
    //    promise._then(params);
    //};
    //return dsl;
    return promise;
}

module.exports = DSL = function(define){
    var dsl = {};

    var dslMethodConvertFunction = function(asyncFunction, callbackNotDeclared){
        var arity = asyncFunction.length;
        if(callbackNotDeclared){
            arity++;
        }
        return function(){
            var deferred = new Deferred();
            arguments.length = arity;
            arguments[arity - 1] = function(error, result){
                if(error) {
                    deferred.emitError(error);
                }
                else {
                    if(arguments.length > 2){
                        // if there are multiple success values, we return an array
                        Array.prototype.shift.call(arguments, 1);
                        deferred.emitSuccess(arguments);
                    }
                    else{
                        deferred.emitSuccess(result);
                    }
                }
            };
            asyncFunction.apply(this, arguments);
            return dslfiyPromise(deferred.promise,dsl);
        };
    };

    for(var i in define){
        dsl[i] =  dslMethodConvertFunction(define[i]);
    }

    return dsl;
}